package com.example.hw_3.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hw_3.common.Result;
import com.example.hw_3.entity.HwFacilityToilet;
import com.example.hw_3.service.HwFacilityToiletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/toilet")
public class HwToiletController {

    @Autowired
    private HwFacilityToiletService hwFacilityToiletService;

    /**
     * 查询所有公厕信息
     */
    @GetMapping("/list")
    public Result<List<HwFacilityToilet>> listAllToilets() {
        List<HwFacilityToilet> toilets = hwFacilityToiletService.list();
        return Result.success("查询所有公厕成功", toilets);
    }


    /**
     * 根据 ID 查询公厕信息
     */
    @GetMapping("/get/{id}")
    public Result<HwFacilityToilet> getById(@PathVariable Long id) {
        HwFacilityToilet toilet = hwFacilityToiletService.getById(id);
        if (toilet != null) {
            return Result.success("查询成功", toilet);
        } else {
            return Result.error("未找到对应的公厕信息");
        }
    }

    /**
     * 新增公厕信息
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody HwFacilityToilet toilet) {
        boolean saved = hwFacilityToiletService.save(toilet);
        return saved ? Result.success("添加成功", null) : Result.error("添加失败");
    }

    /**
     * 修改公厕信息
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody HwFacilityToilet toilet) {
        boolean updated = hwFacilityToiletService.updateById(toilet);
        return updated ? Result.success("更新成功", null) : Result.error("更新失败");
    }

    /**
     * 根据 ID 删除公厕信息
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Long id) {
        boolean removed = hwFacilityToiletService.removeById(id);
        return removed ? Result.success("删除成功", null) : Result.error("删除失败");
    }

    /**
     *  根据等级查询
     */



    /**
     * 分页查询 + 模糊查询（可选）
     */
    @GetMapping("/page")
    public Result<Page<HwFacilityToilet>> getPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String address,
            @RequestParam(required = false) Integer toiletLevel
    ) {
        Page<HwFacilityToilet> page = new Page<>(pageNum, pageSize);
        QueryWrapper<HwFacilityToilet> wrapper = new QueryWrapper<>();

        if (address != null && !address.isEmpty()) {
            wrapper.like("address", address);
        }
        if (toiletLevel != null) {
            wrapper.eq("toilet_level", toiletLevel);
        }

        Page<HwFacilityToilet> resultPage = hwFacilityToiletService.page(page, wrapper);
        return Result.success("分页查询成功", resultPage);
    }

}
